from decimal import Decimal
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView

from goods.models import SKU
from .serializers import OrderSettlementSerializer, SaveOrderSerializer

# Create your views here.


class OrderSettlementView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user
        redis_conn = get_redis_connection('cart')
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        cart_selected = redis_conn.smembers('cart_selected_%s' % user.id)
        count_dict = {}
        for sku_id in cart_selected:
            count_dict[int(sku_id)] = int(redis_cart[sku_id])
        sku_obj_list = SKU.objects.filter(id__in=count_dict.keys())
        for sku in sku_obj_list:
            sku.count = count_dict[sku.id]
        freight = Decimal('10.00')
        serializer = OrderSettlementSerializer({'freight': freight, 'skus': sku_obj_list})
        return Response(serializer.data)


class SaveOrderView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = SaveOrderSerializer